;$(function() {
	$.subscribe('click_big_editor',__big,false)
	 .subscribe('editor_add_plugin',__add,false)
	 .subscribe('editor_add_image',__image,false)
	 .subscribe('editor_delete_image',__delimg,false)
	 .subscribe('editor_delete_plugin',__delete,false)
	 .subscribe('click_delete_image',__acdelimg,false)
	 .subscribe('click_add_label',__label,false)
	 .subscribe('click_addlabel_submit',__labeladd,false)
	 .subscribe('add_label',__addlabel,false)
	 .subscribe('click_del_label',__labeldel,false)
	 .subscribe('click_feed_submit',__submit,false);
	var $editorbox = $("div.editorbox"),labelarr = [];
	function __big(t,e,action) {
		$(t).closest(".editorbox").removeClass("editor_s");
		if($(t).is("textarea")) {
			$text.focus();
		} else {
			$.publish('click_add_label' , $title.find("a.ac_add_label")[0]);
		}
	}
	function __labeldel(t,e,action) {
		var prev = t && t.previousSibling;
		if(prev) {
			var val = prev.nodeValue;
			labelarr = $.trim((' ' + labelarr.join(' ') + ' ').replace(' ' + val + ' ' , ' ')).split(' ');
			if(labelarr.length == 1 && labelarr[0] == '') {
				labelarr.length = 0;
			}
			$(t).closest("span.tags").fadeOut(function() {
				$(this).remove();
			});
		}
	}
	function __add(data) {
		var html = plugin;
		for(var key in data) {
			html = html.replace("{" + key + "}" , data[key]);
		}
		$appsec.html(html);
		$.publish('editor_add_' + data.type,data);
	}
	function __image() {
		var val = $.trim($text.val());
		if(val == '') {
			$text.val('分享图片').triggerHandler("keyup");
		}
	}
	function __acdelimg(t,e,action) {
		var srv = $(t).attr("srv");
		$.get(srv,{},function() {},"json");
		$.publish('editor_delete_image');
	}
	function __delete() {
		$appsec.empty();
		$.UI.hide("image");
		labelarr.length = 0;
		$title.find("span.tags").remove();
	}
	function __delimg() {
		$.publish('ui_hide');
		var val = $.trim($text.val());
		if(val == '分享图片') {
			$text.val('').triggerHandler("keyup");
		}
	}
	function __label() {
		if(labelarr.length == 5) {
			$.alert('<div style="width:200px;text-align:center;"><p style="font-size:12px;">对不起，最多添加五个标签</p></div>' , {liveTime:0})
		} else {
			var $box = $.alert('<div style="width:300px;font-size:14px;padding:10px;"><p style="margin-bottom:10px;">请为你想说的话贴个标签吧！标签可以使用空格进行分割。</p><input maxlength="80" type="text" style="height:18px;line-height:18px;width:230px;background-color:#FFFFFF;border:1px solid #89C5E3;"/><button type="button" class="b-default ac_addlabel_submit" style="margin-left:10px;"><span><b>确定</b></span></button><p style="margin-top:3px;font-size:12px;display:none;" class="error">请填写标签</p></div>' , {liveTime:0});
			$box.find("input").focus();
		}
	}
	function __labeladd(t,e,action) {
		var $t = $(t);
		var $div = $t.closest("div");
		var val = $div.find("input[type='text']").val();
		var $error = $div.find("p.error");
		if(!val) {
			showLabelError($error , '请输入标签');
		} else {
			var error = RegTestLabel(val);
			if(error) {
				showLabelError($error , '最多可添加5个标签，每个标签最多8个字');
			} else {
				error = CheckRepeatLabel(val);
				if(error) {
					showLabelError($error , '不能添加重复标签');
				} else {
					$error.hide();
					$.publish('ui_hide');
					$.publish('add_label' , val);
				}
			}
		}
	}
	function showLabelError($t,msg) {
		$t.hide().html(msg).fadeIn();
	}
	function CheckRepeatLabel(str) {
		var arr = SplitLabel(str);
		Array.prototype.push.apply(arr , labelarr);
		var obj = {};
		for(var key in arr) {
			obj[arr[key]] = 1;
		}
		var count = 0;
		for(var key in obj) {
			count ++;
		}
		return count != arr.length;
	}
	function RegTestLabel(str) {
		var reg = /^[\u3000\s]*[a-zA-Z0-9_\-\u4e00-\u9fa5]{1,8}([\u3000\s]+[a-zA-Z0-9_\-\u4e00-\u9fa5]{1,8}){0,4}[\u3000\s]*$/;
		if(reg.test(str)) {
			var arr = SplitLabel(str);
			Array.prototype.push.apply(arr , labelarr);
			return arr.length > 5;
		} else {
			return true;
		}
	}
	function SplitLabel(str) {
		return str.replace(/^[\u3000\s]+|[\u3000\s]+$/g , '').split(/[\u3000\s]+/);
	}
	function __addlabel(val) {
		var arr = SplitLabel(val);
		var htmlArr = [];
		var tmp = '<span class="tags">#tagshort#<em>#taglong#<a href="javascript:void(0)" class="ac_del_label" title="点击删除标签"> X</a></em></span>';
		for(var i = 0 ; i < arr.length ; i++) {
			var len = arr[i].length;
			if(len > 4) {
				htmlArr.push(tmp.replace("#tagshort#" , arr[i].substring(0,4) + "...").replace("#taglong#" , arr[i]));
			} else {
				htmlArr.push(tmp.replace("#tagshort#" , arr[i]).replace("#taglong#" , arr[i]));
			}
		}
		Array.prototype.push.apply(labelarr , arr);
		$("#need_shai").after($(htmlArr.join(' ')));
	}
	var $appsec = $("#appsec_b");
	var plugin = $appsec.html();
	$appsec.empty();
	var $text = $("#dd_textarea");
	var $app = $("#dd_appsec");
	var $num = $app.find("span.txtnum");
	var $title = $app.prevAll("h2.title");
	$title.delegate("span.tags" , "mouseover" , function() {
		$(this).addClass("hover");
	}).delegate("span.tags em" , "mouseout" , function() {
		$(this).closest("span.tags").removeClass("hover").siblings("span.tags").removeClass("hover");
	});
	$text.textbox({
		maxLength: $num.html(),
		overWrite:true,
		onInput: function(event, status) {
			str = (status.leftLength>=0)?status.leftLength:"<font color='red'>超出"+ (-status.leftLength) + '字</font>';
			$num.html(str);
		}
	});
	var $imgicon = $app.find("a.addpic");
	$imgicon.upload({
		action:"../UploadServlet",
		name : "filename",
		successFun : function(json) {
			$.publish("editor_add_plugin" , json);
		}
	});
	function splash() {
		$num.fadeOut("fast").fadeIn("fast").fadeOut("fast").fadeIn("fast");
	}
	function __getData(text) {
		var data = {};
		data.text = text;
		data.label = labelarr.join(' ');
		$appsec.find("input[type='hidden']").each(function() {
			data[this.name] = this.value;
		});
		return data;
	}
	function __submit(t,e,action) {
		var $t = $(t);
		var issubmit = $t.data("feed.submit");
		if(!issubmit) {
			var text = $.trim($text.val());
			if(!text) {
				$t.errormsg('请输入您要发送的内容' , {direction:"left"});
			} else {
				var status = $num.html();
				if(!/^\d+$/.test(status)) {
					splash();
				} else {
					var url = $t.attr("srv");
					$t.data("feed.submit",true);
					$text.attr("disabled" , true);
					var _data = __getData(text);
					$.ajax({
						url : url, 
						type : "POST",
						data : _data,
						dataType : "json",
						timeout : 15000,
						success : function(d) {
							$text.attr("disabled" , false);
							$t.removeData("feed.submit");
							var code = d.code;
							if(code) {
								$t.errormsg(d.msg , {direction : "left"});
							} else {
								$.publish("feed_create" , d)
								 .publish("editor_delete_plugin");
								$text.val('').triggerHandler("keyup");
								$t.successmsg('<span class="icon_pigeon">'+d.msg+'</span>',{direction:"left"});								
							}
						},
						error : function() {
							$text.attr("disabled" , false);
							$t.removeData("feed.submit").errormsg('与服务器通讯失败，请稍后重试。',{direction:"left"});
						}
					});
				}
			}
		}
	}	
});